import PySimpleGUI as sg
import re
import os

mirror_sources = {
    '清华源': 'https://pypi.tuna.tsinghua.edu.cn/simple/',
    '阿里源': 'https://mirrors.aliyun.com/pypi/simple/',
    '中科大源': 'https://pypi.mirrors.ustc.edu.cn/simple/',
    '豆瓣': 'http://pypi.douban.com/simple/',
    '腾讯': 'http://mirrors.cloud.tencent.com/pypi/simple/',
    '华为': 'https://repo.huaweicloud.com/repository/pypi/simple',
    '北大': 'https://mirrors.pku.edu.cn/pypi/web/simple/',
    '哈工大': 'https://mirrors.hit.edu.cn/pypi/web/simple/',
    '大连东软': 'https://mirrors.neusoft.edu.cn/pypi/web/simple/'
}

class CreateGui():
    
    def create_select_gui(self):
        sg.theme("DefaultNoMoreNagging")
        one_layout = [[
            sg.Radio(key, group_id=1, font=('Helvetica', 12), enable_events=True, key=key)
            for key in mirror_sources.keys()
        ], [
            sg.Button('确定', tooltip='选择镜像源', button_color=('white', 'black'), size=5, key='select')
        ]]
        window = sg.Window('Resizable Window', one_layout, resizable=True)
        while True:
            event, values = window.read(timeout=100)
            if event == sg.WINDOW_CLOSED:
                window.close()
                break
            if event == 'select':
                selected_source = next((key for key, val in values.items() if val), None)
                self.create_error_or_succeed_gui(selected_source)

    def create_error_or_succeed_gui(self, selected_source):
        if selected_source:
            trusted_host = re.search(r"//(.*?)/", mirror_sources[selected_source])
            pip_ini = f'''[global]
timeout = 6000
index-url = {mirror_sources[selected_source]}
trusted-host = {trusted_host.group(1)}'''

            pip_path = os.path.join(os.path.expandvars('%APPDATA%'), 'pip')
            os.makedirs(pip_path, exist_ok=True)
            with open(os.path.join(pip_path, 'pip.ini'), 'w') as fp:
                fp.write(pip_ini)

            sg.popup(f'pip源更新完成-->{selected_source}镜像源')
        else:
            sg.popup('至少选择一个源')

if __name__ == '__main__':
    CreateGui().create_select_gui()
